<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"llmysnow.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="介绍RSA、MD5、SHA、AES 等加密算法在 Vue 中如何使用">
<meta property="og:type" content="article">
<meta property="og:title" content="前后端 JS 加密常用方法（非对称加密、对称加密）">
<meta property="og:url" content="http://llmysnow.top/posts/9f5130f2/index.html">
<meta property="og:site_name" content="奇幻的梦之旅">
<meta property="og:description" content="介绍RSA、MD5、SHA、AES 等加密算法在 Vue 中如何使用">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/company-img/rsa%E5%85%AC%E9%92%A5%E7%A7%81%E9%92%A5.jpg">
<meta property="og:image" content="https://gitee.com/lilyn/pic/raw/master/js-img/%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%92%8C%E5%AE%A2%E6%88%B7%E7%AB%AF%E6%8E%A5%E5%8F%A3%E5%8A%A0%E5%AF%86.png">
<meta property="article:published_time" content="2021-05-06T08:36:02.084Z">
<meta property="article:modified_time" content="2022-04-23T11:27:04.412Z">
<meta property="article:author" content="LiLyn">
<meta property="article:tag" content="Vue">
<meta property="article:tag" content="RSA">
<meta property="article:tag" content="MD5">
<meta property="article:tag" content="SHA">
<meta property="article:tag" content="AES">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lilyn/pic/raw/master/company-img/rsa%E5%85%AC%E9%92%A5%E7%A7%81%E9%92%A5.jpg">

<link rel="canonical" href="http://llmysnow.top/posts/9f5130f2/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>前后端 JS 加密常用方法（非对称加密、对称加密） | 奇幻的梦之旅</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="奇幻的梦之旅" type="application/atom+xml">
</head>
<!--即时预加载技术，在用户点击之前预先加载页面-->
<script src="https://cdn.jsdelivr.net/gh/TRHX/CDN-for-itrhx.com@2.0.2/js/instantclick-1.2.2.js" type="module"></script>
<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	  <!--<a target="_blank" rel="noopener" href="https://github.com/llwodexue" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>-->
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">奇幻的梦之旅</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">http://llmysnow.top/</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://llmysnow.top/posts/9f5130f2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/logo.jpg">
      <meta itemprop="name" content="LiLyn">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="奇幻的梦之旅">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          前后端 JS 加密常用方法（非对称加密、对称加密）
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-05-06 16:36:02" itemprop="dateCreated datePublished" datetime="2021-05-06T16:36:02+08:00">2021-05-06</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>14k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>13 分钟</span>
            </span>
            <div class="post-description">介绍RSA、MD5、SHA、AES 等加密算法在 Vue 中如何使用</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="对称加密"><a href="#对称加密" class="headerlink" title="对称加密"></a>对称加密</h1><p>对称加密一大缺点是密钥的管理与分配，换句话说，如何把密钥发送到需要解密你的消息的人的手里是一个问题。在发送密钥的过程中，密钥有很大的风险会被黑客拦截。现实中通常的做法是将对称加密的密钥进行非对称加密，然后传送给需要它的人</p>
<p>彩虹表是对于散列函数做逆运算的表（空间换时间），密码安全度比较低是可以用彩虹表碰撞去破解的，可以在 <a target="_blank" rel="noopener" href="https://freerainbowtables.com/">Free Rainbow Tables</a> 上下载进行试验，如果试图解密，可以使用 <a target="_blank" rel="noopener" href="https://cmd5.com/">CMD5</a> 进行解密</p>
<h2 id="不可逆加密（MD5-SHA）"><a href="#不可逆加密（MD5-SHA）" class="headerlink" title="不可逆加密（MD5 SHA）"></a>不可逆加密（MD5 SHA）</h2><p>node 中有原生 crypto 模块，该模块提供了 hash、hmac、加密解密等一整套封装。因为是 node 中的模块，所以需要使用 <code>const crypto = require(&#39;crypto&#39;)</code> 来引入</p>
<p>MD5、SHA1 也成散列算法</p>
<h3 id="crypto-进行-MD5-SHA-加密"><a href="#crypto-进行-MD5-SHA-加密" class="headerlink" title="crypto 进行 MD5 SHA 加密"></a>crypto 进行 MD5 SHA 加密</h3><p>hash 算法又称摘要算法，该算法可以将任意长度的数据，转换为固定长度的 hash 值，且具有不可逆性</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(crypto.getHashes())</span><br></pre></td></tr></table></figure>

<p>使用 <code>getHashes</code> 方法，可以获取到所有支持 hash 算法的一个数组</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">[</span><br><span class="line">  <span class="string">&#x27;RSA-MD4&#x27;</span>, <span class="string">&#x27;RSA-MD5&#x27;</span>, <span class="string">&#x27;RSA-MDC2&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;RSA-RIPEMD160&#x27;</span>, <span class="string">&#x27;RSA-SHA1&#x27;</span>, <span class="string">&#x27;RSA-SHA1-2&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;RSA-SHA224&#x27;</span>, <span class="string">&#x27;RSA-SHA256&#x27;</span>, <span class="string">&#x27;RSA-SHA3-224&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;RSA-SHA3-256&#x27;</span>, <span class="string">&#x27;RSA-SHA3-384&#x27;</span>, <span class="string">&#x27;RSA-SHA3-512&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;RSA-SHA384&#x27;</span>, <span class="string">&#x27;RSA-SHA512&#x27;</span>, <span class="string">&#x27;RSA-SHA512/224&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;RSA-SHA512/256&#x27;</span>, <span class="string">&#x27;RSA-SM3&#x27;</span>, <span class="comment">// ....</span></span><br><span class="line">  <span class="string">&#x27;md5&#x27;</span>, <span class="string">&#x27;md5-sha1&#x27;</span>, <span class="string">&#x27;md5WithRSAEncryption&#x27;</span>, <span class="comment">// ...</span></span><br><span class="line">  <span class="string">&#x27;sha1&#x27;</span>, <span class="string">&#x27;sha1WithRSAEncryption&#x27;</span>, <span class="string">&#x27;sha224&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;sha224WithRSAEncryption&#x27;</span>, <span class="string">&#x27;sha256&#x27;</span>, <span class="string">&#x27;sha256WithRSAEncryption&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;sha3-224&#x27;</span>, <span class="string">&#x27;sha3-256&#x27;</span>, <span class="string">&#x27;sha3-384&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;sha3-512&#x27;</span>, <span class="string">&#x27;sha384&#x27;</span>, <span class="string">&#x27;sha384WithRSAEncryption&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;sha512&#x27;</span>, <span class="string">&#x27;sha512-224&#x27;</span>, <span class="string">&#x27;sha512-224WithRSAEncryption&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;sha512-256&#x27;</span>, <span class="string">&#x27;sha512-256WithRSAEncryption&#x27;</span>, <span class="string">&#x27;sha512WithRSAEncryption&#x27;</span>,</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>这些 hash 算法，我们平常用的比较多的是：<code>md5</code>、<code>sha1</code>、<code>sha256</code> 等。这里我们可以简单封装一下，根据不同摘要算法生成不同 hash 值</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> createHash = <span class="function">(<span class="params">type, str</span>) =&gt;</span> crypto.createHash(type).update(str).digest(<span class="string">&#x27;hex&#x27;</span>)</span><br><span class="line"></span><br><span class="line">[<span class="string">&#x27;md5&#x27;</span>, <span class="string">&#x27;sha1&#x27;</span>, <span class="string">&#x27;sha256&#x27;</span>].forEach(<span class="function"><span class="params">type</span> =&gt;</span> &#123;</span><br><span class="line">  createHash(type, <span class="string">&#x27;123&#x27;</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">md5 202cb962ac59075b964b07152d234b70</span></span><br><span class="line"><span class="comment">sha1 40bd001563085fc35165329ea1ff5c5ecbdbbeef</span></span><br><span class="line"><span class="comment">sha256 a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h3 id="上面版本的加盐和-hmac-算法"><a href="#上面版本的加盐和-hmac-算法" class="headerlink" title="* 上面版本的加盐和 hmac 算法"></a>* 上面版本的加盐和 hmac 算法</h3><p>如果密码安全强度过低，是很容易被彩虹表碰撞上的，所以一般还会做一层加盐加字符串的处理，这样碰撞成功的概率就大大减少了</p>
<p>这里以 MD5 加密方式举例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> createHash = <span class="function">(<span class="params">type, str</span>) =&gt;</span> crypto.createHash(type).update(str).digest(<span class="string">&#x27;hex&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> psw = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"><span class="keyword">const</span> md5 = <span class="function"><span class="params">str</span> =&gt;</span> createHash(<span class="string">&#x27;md5&#x27;</span>, str)</span><br><span class="line"><span class="keyword">const</span> encryptPassword = <span class="function">(<span class="params">salt, password</span>) =&gt;</span> md5(salt + <span class="string">&#x27;@3#!8^k.j$0#qr&#x27;</span> + password)</span><br><span class="line"><span class="keyword">const</span> salt = <span class="built_in">Math</span>.random() * <span class="number">99999</span> + <span class="keyword">new</span> <span class="built_in">Date</span>().getTime()</span><br><span class="line"></span><br><span class="line">encryptPassword(salt, psw) <span class="comment">// 5927975bb4e8453b54e244ae4640426f</span></span><br></pre></td></tr></table></figure>

<p>crypto 里有 <code>createHmac()</code> 方法，hmac 类似加盐版 hash 算法，hmac 是密钥相关的哈希运算消息认证码（Hash-basees Message Authentication Code）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> salt = (<span class="built_in">Math</span>.random() * <span class="number">99999</span>).toString() + <span class="keyword">new</span> <span class="built_in">Date</span>().getTime()</span><br><span class="line"><span class="keyword">const</span> createHmac = <span class="function">(<span class="params">type, str</span>) =&gt;</span> crypto.createHmac(type, salt).update(str).digest(<span class="string">&#x27;hex&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> psw = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"><span class="keyword">const</span> md5 = <span class="function"><span class="params">str</span> =&gt;</span> createHmac(<span class="string">&#x27;md5&#x27;</span>, str)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(md5(salt, psw)) <span class="comment">// c9bce0c58ec62881aa5774a7d304b40a</span></span><br></pre></td></tr></table></figure>

<h3 id="blueimp-md5-进行-MD5-加密"><a href="#blueimp-md5-进行-MD5-加密" class="headerlink" title="blueimp-md5 进行 MD5 加密"></a>blueimp-md5 进行 MD5 加密</h3><p>接下来简单说一下其他可能会用到的加密包</p>
<ul>
<li>注意：使用两次 md5 加密也是不安全的，也能被彩虹表碰撞到</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* npm i blueimp-md5 */</span></span><br><span class="line"><span class="keyword">import</span> md5 <span class="keyword">from</span> <span class="string">&#x27;blueimp-md5&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">passTrans</span>(<span class="params">pass</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> md5(pass)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(passTrans(txt)) <span class="comment">// 202cb962ac59075b964b07152d234b70</span></span><br></pre></td></tr></table></figure>

<h3 id="sha-进行-SHA-加密"><a href="#sha-进行-SHA-加密" class="headerlink" title="sha 进行 SHA 加密"></a>sha 进行 SHA 加密</h3><p>SHA 家族的五个算法，分别是 SHA-1、SHA-224、SHA-256、SHA-384，和 SHA-512，由美国国家安全局（NSA）所规划，并由美国国家规范与技能研究院（NIST）发布，这里只对 SHA-1 和 SHA-256 进行演示</p>
<ul>
<li>SHA-1</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* npm i js-sha1 */</span></span><br><span class="line"><span class="keyword">import</span> sha1 <span class="keyword">from</span> <span class="string">&#x27;js-sha1&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">passTrans</span>(<span class="params">pass</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> sha1(pass)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(passTrans(txt)) <span class="comment">// 40bd001563085fc35165329ea1ff5c5ecbdbbeef</span></span><br></pre></td></tr></table></figure>

<ul>
<li>SHA-256</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* npm i js-sha256 */</span></span><br><span class="line"><span class="keyword">import</span> &#123; sha256 &#125; <span class="keyword">from</span> <span class="string">&#x27;js-sha256&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">passTrans</span>(<span class="params">pass</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> sha256(pass)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(passTrans(txt)) <span class="comment">// a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3</span></span><br></pre></td></tr></table></figure>



<h2 id="可逆加密（AES-DES-BASE64）"><a href="#可逆加密（AES-DES-BASE64）" class="headerlink" title="可逆加密（AES DES BASE64）"></a>可逆加密（AES DES BASE64）</h2><h3 id="crypto-进行-AES-加密"><a href="#crypto-进行-AES-加密" class="headerlink" title="crypto 进行 AES 加密"></a>crypto 进行 AES 加密</h3><p>上述这些方法都是不可逆 hash 加密算法，接下来说一下可加密解密的算法。常见的有 <code>AES</code>、<code>DES</code>、<code>BASE64</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(crypto.getCiphers())</span><br></pre></td></tr></table></figure>

<p>使用 <code>getCiphers</code> 方法，可以获取到所有支持 cipher 算法的一个数组</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">[</span><br><span class="line">  <span class="string">&#x27;aes-128-cbc&#x27;</span>, <span class="string">&#x27;aes-128-ccm&#x27;</span>, <span class="string">&#x27;aes-128-cfb&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-128-cfb1&#x27;</span>, <span class="string">&#x27;aes-128-cfb8&#x27;</span>, <span class="string">&#x27;aes-128-ctr&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-128-ecb&#x27;</span>, <span class="string">&#x27;aes-128-gcm&#x27;</span>, <span class="string">&#x27;aes-128-ocb&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-128-ofb&#x27;</span>, <span class="string">&#x27;aes-128-xts&#x27;</span>, <span class="string">&#x27;aes-192-cbc&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-192-ccm&#x27;</span>, <span class="string">&#x27;aes-192-cfb&#x27;</span>, <span class="string">&#x27;aes-192-cfb1&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-192-cfb8&#x27;</span>, <span class="string">&#x27;aes-192-ctr&#x27;</span>, <span class="string">&#x27;aes-192-ecb&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-192-gcm&#x27;</span>, <span class="string">&#x27;aes-192-ocb&#x27;</span>, <span class="string">&#x27;aes-192-ofb&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-256-cbc&#x27;</span>, <span class="string">&#x27;aes-256-ccm&#x27;</span>, <span class="string">&#x27;aes-256-cfb&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-256-cfb1&#x27;</span>, <span class="string">&#x27;aes-256-cfb8&#x27;</span>, <span class="string">&#x27;aes-256-ctr&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-256-ecb&#x27;</span>, <span class="string">&#x27;aes-256-gcm&#x27;</span>, <span class="string">&#x27;aes-256-ocb&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes-256-ofb&#x27;</span>, <span class="string">&#x27;aes-256-xts&#x27;</span>, <span class="string">&#x27;aes128&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes128-wrap&#x27;</span>, <span class="string">&#x27;aes192&#x27;</span>,      <span class="string">&#x27;aes192-wrap&#x27;</span>,</span><br><span class="line">  <span class="string">&#x27;aes256&#x27;</span>,      <span class="string">&#x27;aes256-wrap&#x27;</span>, <span class="string">&#x27;aria-128-cbc&#x27;</span>,</span><br><span class="line">  <span class="comment">// ....</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>cryoto 模块中提供了 <code>createCipheriv</code> 和 <code>createDecipheriv</code> 来进行加密和解密的功能，这两个方法都接收 3 个参数：</p>
<ol>
<li><p>algorithm 同于指定加密算法</p>
<p><code>aes-128-cbc</code>  算法是 128</p>
</li>
<li><p>key：加密解密的密钥，密钥必须是 <code>8/16/32</code> 位</p>
<p>如果加密算法是 128，对应密钥是 16 位</p>
<p>如果加密算法是 256，对应密钥是 32 位</p>
</li>
<li><p>iv：参数可选，用于指定加密时所用的向量，规则与 key 一样</p>
</li>
</ol>
<p>常用的模式是：ECB、CBC、CFB、OFB。详细可见：<a target="_blank" rel="noopener" href="https://blog.csdn.net/jerry81333/article/details/78336616">块加密 工作模式 ECB、CBC、PCBC、CFB、OFB、CTR</a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> crypto = <span class="built_in">require</span>(<span class="string">&#x27;crypto&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> AES_ALGORITHM = <span class="string">&#x27;aes-128-cbc&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> key = <span class="string">&#x27;encode@3#!8^k.j$&#x27;</span></span><br><span class="line"><span class="keyword">const</span> iv = <span class="string">&#x27;vector@3#!8^k.j$&#x27;</span></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">encrypt</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> encrypted = <span class="string">&#x27;&#x27;</span></span><br><span class="line">  <span class="keyword">const</span> cipher = crypto.createCipheriv(AES_ALGORITHM, key, iv)</span><br><span class="line">  encrypted += cipher.update(data, <span class="string">&#x27;utf8&#x27;</span>, <span class="string">&#x27;base64&#x27;</span>)</span><br><span class="line">  encrypted += cipher.final(<span class="string">&#x27;base64&#x27;</span>)</span><br><span class="line">  <span class="keyword">return</span> encrypted</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">decrypt</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> decrypted = <span class="string">&#x27;&#x27;</span></span><br><span class="line">  <span class="keyword">const</span> cipher = crypto.createDecipheriv(AES_ALGORITHM, key, iv)</span><br><span class="line">  decrypted += cipher.update(data, <span class="string">&#x27;base64&#x27;</span>, <span class="string">&#x27;utf8&#x27;</span>)</span><br><span class="line">  decrypted += cipher.final(<span class="string">&#x27;utf8&#x27;</span>)</span><br><span class="line">  <span class="keyword">return</span> decrypted</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> sign = encrypt(txt)</span><br><span class="line"><span class="keyword">const</span> _src = decrypt(sign)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;加密：&#x27;</span>, sign)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;解密：&#x27;</span>, _src)</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">加密： lVKUZlJeTrkHc3Qf5s0KPw==</span></span><br><span class="line"><span class="comment">解密： 123</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h3 id="crypto-js-进行-AES-加密"><a href="#crypto-js-进行-AES-加密" class="headerlink" title="* crypto-js 进行 AES 加密"></a>* crypto-js 进行 AES 加密</h3><p>由于 crypto 是 node 原生的，很多人可能又不习惯，下面介绍另一款 crypto-js 。这个需要 npm 下载，也可以直接去 <a target="_blank" rel="noopener" href="https://github.com/brix/crypto-js">crypto-js GitHub</a> 下载</p>
<p>CryptoJS 在处理前需要对参数进行一下处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> wordArray = CryptoJS.enc.Utf8.parse(utf8String)</span><br><span class="line"><span class="keyword">const</span> wordArray = CryptoJS.enc.Latin1.parse(latin1String)</span><br><span class="line"><span class="keyword">const</span> wordArray = CryptoJS.enc.Hex.parse(hexString)</span><br><span class="line"><span class="keyword">const</span> wordArray = CryptoJS.enc.Base64.parse(base64String)</span><br></pre></td></tr></table></figure>

<p>CryptoJS 加密出的结果是一个对象：<code>CryptoJs.AES.encrypt(src, key, &#123; iv, mode, padding &#125;)</code> ，所以需要对其进行文本处理 <code>toString()</code> 或 <code>+ &#39;&#39;</code></p>
<ul>
<li><p>key 是密钥，可以是接口返回的</p>
</li>
<li><p>iv 是密钥偏移量，一般都是接口返回的</p>
</li>
<li><p>mode：支持 CBC、CFB、CTR、ECB、OFB，默认 CBC</p>
<p>详细可见：<a target="_blank" rel="noopener" href="https://blog.csdn.net/jerry81333/article/details/78336616">块加密 工作模式 ECB、CBC、PCBC、CFB、OFB、CTR</a></p>
<p>ECB 模式下，向量 iv 是没有用的。ECB 加密原理：根据加密块的大小分成若干块，之后将每块使用相同的秘钥单独加密即可</p>
<p>CBC 模式下，向量 iv 是有用的。CBC 加密原理：每个明文块进行异或后再进行加密，每个密文块都依赖前面的所有明文块</p>
</li>
<li><p>padding ：支持 Pkcs7、AnsiX923、Iso10126、NoPadding、ZeroPadding，默认 Pkcs7</p>
</li>
</ul>
<p>CryptoJS 解密密文必须是 BASE64 编码</p>
<blockquote>
<p>详细原理可以参考：<a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_28205153/article/details/55798628">AES加密算法的详细介绍与实现</a></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* npm i crypto-js */</span></span><br><span class="line"><span class="comment">// import CryptoJS from &#x27;crypto-js&#x27;</span></span><br><span class="line"><span class="keyword">const</span> CryptoJS = <span class="built_in">require</span>(<span class="string">&#x27;crypto-js&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> keyStr = <span class="string">&#x27;encode@3#!8^k.j$&#x27;</span></span><br><span class="line"><span class="keyword">const</span> ivStr = <span class="string">&#x27;vector@3#!8^k.j$&#x27;</span></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">encrypt</span>(<span class="params">data, keyS, ivS</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> key = keyS || keyStr</span><br><span class="line">  <span class="keyword">let</span> iv = ivS || ivStr</span><br><span class="line">  key = CryptoJS.enc.Utf8.parse(key)</span><br><span class="line">  iv = CryptoJS.enc.Utf8.parse(iv)</span><br><span class="line">  <span class="keyword">const</span> src = CryptoJS.enc.Utf8.parse(data)</span><br><span class="line">  <span class="keyword">const</span> cipher = CryptoJS.AES.encrypt(src, key, &#123;</span><br><span class="line">    iv: iv, <span class="comment">// 初始向量</span></span><br><span class="line">    mode: CryptoJS.mode.CBC, <span class="comment">// 加密模式</span></span><br><span class="line">    padding: CryptoJS.pad.Pkcs7, <span class="comment">// 填充方式</span></span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">const</span> encrypted = cipher.toString()</span><br><span class="line">  <span class="keyword">return</span> encrypted</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">decrypt</span>(<span class="params">data, keyS, ivS</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> key = keyS || keyStr</span><br><span class="line">  <span class="keyword">let</span> iv = ivS || ivStr</span><br><span class="line">  key = CryptoJS.enc.Utf8.parse(key)</span><br><span class="line">  iv = CryptoJS.enc.Utf8.parse(iv)</span><br><span class="line">  <span class="keyword">const</span> cipher = CryptoJS.AES.decrypt(data, key, &#123;</span><br><span class="line">    iv: iv,</span><br><span class="line">    mode: CryptoJS.mode.CBC,</span><br><span class="line">    padding: CryptoJS.pad.Pkcs7,</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="keyword">const</span> decrypted = cipher.toString(CryptoJS.enc.Utf8) <span class="comment">// 返回的是加密之前的原始数据-&gt;字符串类型</span></span><br><span class="line">  <span class="keyword">return</span> decrypted</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> sign = encrypt(txt)</span><br><span class="line"><span class="keyword">const</span> _src = decrypt(sign)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;加密：&#x27;</span>, sign)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;解密：&#x27;</span>, _src)</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">加密： lVKUZlJeTrkHc3Qf5s0KPw==</span></span><br><span class="line"><span class="comment">解密： 123</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h3 id="crypto-js-进行-DES-加密"><a href="#crypto-js-进行-DES-加密" class="headerlink" title="crypto-js 进行 DES 加密"></a>crypto-js 进行 DES 加密</h3><p>DES -&gt; TripleDES -&gt; RC4 -&gt; AES（安全性会更高一些）</p>
<ul>
<li>DES 其实只是把之前写 AES 的部分改成 DES</li>
<li>https （SSL 使用 40 位关键字作为 RC4 流加密算法）</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* npm i crypto-js */</span></span><br><span class="line"><span class="comment">// import CryptoJS from &#x27;crypto-js&#x27;</span></span><br><span class="line"><span class="keyword">const</span> CryptoJS = <span class="built_in">require</span>(<span class="string">&#x27;crypto-js&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> keyStr = <span class="string">&#x27;encode@3#!8^k.j$&#x27;</span></span><br><span class="line"><span class="keyword">const</span> ivStr = <span class="string">&#x27;vector@3#!8^k.j$&#x27;</span></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">encrypt</span>(<span class="params">data, keyS, ivS</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> key = keyS || keyStr</span><br><span class="line">  <span class="keyword">let</span> iv = ivS || ivStr</span><br><span class="line">  key = CryptoJS.enc.Utf8.parse(key)</span><br><span class="line">  iv = CryptoJS.enc.Utf8.parse(iv)</span><br><span class="line">  <span class="keyword">const</span> src = CryptoJS.enc.Utf8.parse(data)</span><br><span class="line">  <span class="keyword">return</span> CryptoJS.DES.encrypt(src, key, &#123;</span><br><span class="line">    iv: iv, <span class="comment">// 初始向量</span></span><br><span class="line">    mode: CryptoJS.mode.CBC, <span class="comment">// 加密模式</span></span><br><span class="line">    padding: CryptoJS.pad.Pkcs7, <span class="comment">// 填充方式</span></span><br><span class="line">  &#125;).toString()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">decrypt</span>(<span class="params">data, keyS, ivS</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> key = keyS || keyStr</span><br><span class="line">  <span class="keyword">let</span> iv = ivS || ivStr</span><br><span class="line">  key = CryptoJS.enc.Utf8.parse(key)</span><br><span class="line">  iv = CryptoJS.enc.Utf8.parse(iv)</span><br><span class="line">  <span class="keyword">return</span> CryptoJS.DES.decrypt(data, key, &#123;</span><br><span class="line">    iv: iv,</span><br><span class="line">    mode: CryptoJS.mode.CBC,</span><br><span class="line">    padding: CryptoJS.pad.Pkcs7,</span><br><span class="line">  &#125;).toString(CryptoJS.enc.Utf8)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> sign = encrypt(txt)</span><br><span class="line"><span class="keyword">const</span> _src = decrypt(sign)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;加密：&#x27;</span>, sign)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;解密：&#x27;</span>, _src)</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">加密： OaCOFkaXIUc=</span></span><br><span class="line"><span class="comment">解密： 123</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h3 id="crypto-js-进行-BASE64-加密"><a href="#crypto-js-进行-BASE64-加密" class="headerlink" title="crypto-js 进行 BASE64 加密"></a>crypto-js 进行 BASE64 加密</h3><p>可以使用 window 自带的方法，不过使用这个是有缺陷的（无法处理中文）：</p>
<ul>
<li><code>window.btoa</code> 对字符串进行 BASE64 编码（注意：不能编码中文）</li>
<li><code>window.atob</code> 对 BASE64 字符串进行解码（注意：转换含有中文的 BASE64 编码是不能正确解码的）</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* npm i crypto-js */</span></span><br><span class="line"><span class="comment">// import CryptoJS from &#x27;crypto-js&#x27;</span></span><br><span class="line"><span class="keyword">const</span> CryptoJS = <span class="built_in">require</span>(<span class="string">&#x27;crypto-js&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123算法&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">encrypt</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> encrypted = CryptoJS.enc.Utf8.parse(data)</span><br><span class="line">  <span class="keyword">const</span> cipher = CryptoJS.enc.Base64.stringify(encrypted)</span><br><span class="line">  <span class="keyword">return</span> cipher</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">decrypt</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> decrypted = CryptoJS.enc.Base64.parse(data)</span><br><span class="line">  <span class="keyword">const</span> cipher = decrypted.toString(CryptoJS.enc.Utf8)</span><br><span class="line">  <span class="keyword">return</span> cipher</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> sign = encrypt(txt)</span><br><span class="line"><span class="keyword">const</span> _src = decrypt(sign)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;加密：&#x27;</span>, sign)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;解密：&#x27;</span>, _src)</span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">加密： MTIz566X5rOV</span></span><br><span class="line"><span class="comment">解密： 123算法</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h1 id="非对称加密"><a href="#非对称加密" class="headerlink" title="非对称加密"></a>非对称加密</h1><p>非对称加密会产生一对密钥（公钥负责加密、私钥负责解密），私钥无法解开说明公钥无效（抗抵赖性）。常见算法 RSA（大质数 ）、Elgamal、背包算法、Rabin、D-H、ECC（椭圆曲线加密算法）</p>
<p>如下只对 RSA 算法进行说明</p>
<h2 id="jsencrypt-进行-RSA-加密"><a href="#jsencrypt-进行-RSA-加密" class="headerlink" title="jsencrypt 进行 RSA 加密"></a>jsencrypt 进行 RSA 加密</h2><p>加密算法分为对称加密和非对称加密，AES 是对称加密，RSA 是非对称加密</p>
<ul>
<li>接口加密一般会使用 AES，之所以用 AES 加密是因为效率高</li>
<li>RSA 会慢一些，一般会用做签名认证操作，防止请求被篡改</li>
</ul>
<blockquote>
<p>参考：<a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html">RSA算法原理（一）</a></p>
<p>只能被 1 和本身整除的数叫质数，例如 13，质数是无穷多的，得到两个巨大质数的乘积是简单的事，但想要从该乘积反推出这两个巨大质数却没有任何有效的办法，这种不可逆的单向数学关系，是国际数学界公认的质因数分解难题</p>
<p>Rivest(R)、Shamir(S) 和 Adleman(A) 三人巧妙利用这一假说，设计出 RSA 公钥加密算法的基本原理：</p>
<ol>
<li>让计算机随机生成两个大质数 p 和 q，得出乘积 n</li>
<li>利用 p 和 q 有条件的生成加密密钥 e</li>
<li>通过一系列计算，得到与 n 互为质数的解密密钥 d，置于操作系统才知道的地方</li>
<li>操作系统将 n 和 e 共同作为公钥对外发布，将私钥 d 秘密保存，把初始质数 p 和 q 秘密丢弃</li>
</ol>
</blockquote>
<p>接下来需要生成一下 RSA 密钥对： <a target="_blank" rel="noopener" href="http://web.chacuo.net/netrsakeypair">生成 RSA 密钥对</a>，将生成的公钥私钥复制过去（一般复制公钥即可，私钥给后端）</p>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/company-img/rsa%E5%85%AC%E9%92%A5%E7%A7%81%E9%92%A5.jpg"></p>
<p>jsencrypt 包没有处理 node 中的情况，所以这里就不演示代码了，大家可以去 vue 里尝试一下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* npm i jsencrypt */</span></span><br><span class="line"><span class="keyword">import</span> JSEncrypt <span class="keyword">from</span> <span class="string">&#x27;jsencrypt/bin/jsencrypt&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> publicKey = <span class="string">`非对称加密公钥`</span></span><br><span class="line"><span class="keyword">const</span> privateKey = <span class="string">`非对称加密私钥`</span></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 加密 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">encrypt</span>(<span class="params">pass</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> encrypted = <span class="keyword">new</span> JSEncrypt() <span class="comment">// 创建加密对象实例</span></span><br><span class="line">  encrypted.setPublicKey(publicKey) <span class="comment">// 设置公钥</span></span><br><span class="line">  <span class="keyword">return</span> encrypted.encrypt(pass) <span class="comment">// 对内容进行加密</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 解密 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">decrypt</span>(<span class="params">pass</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> decrypted = <span class="keyword">new</span> JSEncrypt() <span class="comment">// 创建解密对象实例</span></span><br><span class="line">  decrypted.setPrivateKey(privateKey) <span class="comment">// 设置私钥</span></span><br><span class="line">  <span class="keyword">return</span> decrypted.decrypt(pass) <span class="comment">// 拿私钥解密内容</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(decrypt(encrypt(txt))) <span class="comment">// &#x27;123&#x27;</span></span><br></pre></td></tr></table></figure>

<h2 id="node-rsa-进行-RSA-加密"><a href="#node-rsa-进行-RSA-加密" class="headerlink" title="node-rsa 进行 RSA 加密"></a>node-rsa 进行 RSA 加密</h2><p>前端一般用 jsencrypt 做加密，后端（Node）一般用 node-rsa 解密</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> publicKey = key.exportKey(<span class="string">&#x27;pkcs8-public&#x27;</span>).toString(<span class="string">&#x27;base64&#x27;</span>) <span class="comment">// 可以给前端的公钥</span></span><br><span class="line"><span class="keyword">const</span> privateKey = key.exportKey(<span class="string">&#x27;pkcs8-private&#x27;</span>).toString(<span class="string">&#x27;base64&#x27;</span>) <span class="comment">// 私钥</span></span><br></pre></td></tr></table></figure>

<p>为了增强数据交换的安全性，一般会进行签名和验证操作：</p>
<ul>
<li>由于客户端的公钥是公开的，发送请求被拦截（中间人）， <strong>中间人是可以使用公钥对参数加密，替换拦截到的参数密文，发送给服务端</strong> ，这样就导致服务端无法判断得到的请求是否是可信的客户端发送的了（请求头是对的，但是参数被中间人替换了）</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nodeRSA = <span class="built_in">require</span>(<span class="string">&#x27;node-rsa&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 生成一个1024长度的密钥对</span></span><br><span class="line"><span class="keyword">const</span> key = <span class="keyword">new</span> nodeRSA(&#123; <span class="attr">b</span>: <span class="number">1024</span> &#125;)</span><br><span class="line"><span class="keyword">const</span> publicKey = key.exportKey(<span class="string">&#x27;pkcs8-public&#x27;</span>) <span class="comment">// 公钥</span></span><br><span class="line"><span class="keyword">const</span> privateKey = key.exportKey(<span class="string">&#x27;pkcs8-private&#x27;</span>) <span class="comment">// 私钥</span></span><br><span class="line"><span class="keyword">const</span> txt = <span class="string">&#x27;123&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用公钥加密</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">encrypt</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> pubKey = <span class="keyword">new</span> nodeRSA(publicKey, <span class="string">&#x27;pkcs8-public&#x27;</span>)</span><br><span class="line">  <span class="keyword">return</span> pubKey.encrypt(Buffer.from(data), <span class="string">&#x27;base64&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用私钥解密</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">decrypt</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> priKey = <span class="keyword">new</span> nodeRSA(privateKey, <span class="string">&#x27;pkcs8-private&#x27;</span>)</span><br><span class="line">  <span class="keyword">return</span> priKey.decrypt(Buffer.from(data, <span class="string">&#x27;base64&#x27;</span>), <span class="string">&#x27;utf8&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> sign = encrypt(txt)</span><br><span class="line"><span class="keyword">const</span> _src = decrypt(sign)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;加密：&#x27;</span>, sign)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;解密：&#x27;</span>, _src)</span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">加密： fBaBFVPv+96I/r6a2tfPbYWa0yjgJKQ+K2/E9obGNo0dYBOSBzW2PgnPOHX+/pq0wUZPxJzcwt5YcMtOsUNuZAYpaPZJ9o6IOEKj823HBNbyerDMUfU3rINCk2FilRuxFpQPmBZTbSvSumKligdtsh1Vz02DwdRgbJHp5bm4Hjk=</span></span><br><span class="line"><span class="comment">解密： 123</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用私钥对消息签名</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">signRSA</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> priKey = <span class="keyword">new</span> nodeRSA(privateKey, <span class="string">&#x27;pkcs8-private&#x27;</span>)</span><br><span class="line">  <span class="keyword">return</span> priKey.sign(Buffer.from(data), <span class="string">&#x27;hex&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用公钥验证签名</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">verifyRSA</span>(<span class="params">decrypt, signs</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> pubKey = <span class="keyword">new</span> nodeRSA(publicKey, <span class="string">&#x27;pkcs8-public&#x27;</span>)</span><br><span class="line">  <span class="keyword">return</span> pubKey.verify(Buffer.from(decrypt), signs, <span class="string">&#x27;utf8&#x27;</span>, <span class="string">&#x27;hex&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> signature = signRSA(sign)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;私钥签名：&#x27;</span> + signature)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;公钥验证：&#x27;</span> + verifyRSA(sign, signature))</span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">私钥签名：873ae60fa3a5a89850185632b53e54b7c9919d146f2464a857f83679d9862e0612973c891994f6f576d4c04913a8b0a17b9b3adaa3577fcb81d637b2ede0c4a1cffadcaa99b81d09a7edfa69a813cd9f87fe52d96c371f6af533dd5577fdc0f6f7dc6857e1a78d425c0be71f7c440e44e8f932c4ed8890dba007721d10832e92</span></span><br><span class="line"><span class="comment">公钥验证：true</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h1 id="前后端接口加密"><a href="#前后端接口加密" class="headerlink" title="前后端接口加密"></a>前后端接口加密</h1><p>前端需要做的就是 2 件事情：</p>
<ol>
<li><p>统一处理数据的响应，在渲染到页面之前进行解密操作</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">service.interceptors.response.use(</span><br><span class="line">  response =&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (response.config.responseType === <span class="string">&#x27;blob&#x27;</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> response</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">const</span> res = response.data</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> res === <span class="string">&#x27;string&#x27;</span>) &#123;</span><br><span class="line">      <span class="comment">// 对response.data进行处理</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res</span><br><span class="line">  &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
</li>
<li><p>请求的数据发出时，统一加密</p>
<p>get 请求对 data 进行加密</p>
<p>post 请求对 param 进行加密</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">service.interceptors.request.use(</span><br><span class="line">  config =&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (config.method === <span class="string">&#x27;post&#x27;</span>) &#123;</span><br><span class="line">      <span class="keyword">const</span> data = config.data</span><br><span class="line">      <span class="keyword">if</span> (data) &#123;</span><br><span class="line">        <span class="comment">// 对config.data进行处理</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (config.method === <span class="string">&#x27;get&#x27;</span>) &#123;</span><br><span class="line">      <span class="keyword">const</span> params = config.params</span><br><span class="line">      <span class="keyword">if</span> (params) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">Object</span>.keys(params).length !== <span class="number">0</span>) &#123;</span><br><span class="line">          <span class="comment">// 对config.params进行处理</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> config</span><br><span class="line">  &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

</li>
</ol>
<blockquote>
<p>前后端请求加密操作可以参考：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/wangweizhang/p/12883671.html">前后端API交互加密解密（js、Java）</a></p>
</blockquote>
<p>到此为止前后端交互通信已经做了加密操作，接下来最重要的就是如何保证加密的 key 不泄露？</p>
<ul>
<li>服务端啊安全性较高，可以存储在数据库文件或配置文件中，前端就很危险了</li>
</ul>
<p>下面是动态获取加密 key 的方式：</p>
<ul>
<li>用 RSA 加密传输 AES 的秘钥，用 AES 加密数据，两者相互结合优势互补</li>
</ul>
<p><img data-src="https://gitee.com/lilyn/pic/raw/master/js-img/%E6%9C%8D%E5%8A%A1%E7%AB%AF%E5%92%8C%E5%AE%A2%E6%88%B7%E7%AB%AF%E6%8E%A5%E5%8F%A3%E5%8A%A0%E5%AF%86.png"></p>
<ol>
<li>客户端发送请求，服务端用 RSA 生成一对公钥和私钥 pub1、pri1，将公钥 pub1 返给客户端</li>
<li>客户端拿到服务端返回的公钥 pub1 后，先用 RSA 算法生成一对公钥和私钥 pub2、pri2，之后用公钥 pub2 对 pub1 加密，加密之后传输给服务端</li>
<li>服务端收到客户端传输的密文，用私钥 pri1 解密（数据是用 pub1 加密的）拿到客户端生成的公钥 pub2</li>
<li>服务端用 AES 生成加密 key 用公钥 pub2 加密，返给客户端，客户端用 pri2 进行解密。以后服务端数据都通过 AES 加密，客户端用对应的 key 进行解密即可</li>
</ol>

    </div>

    
    
    

	<div>
		  
			
<div class="my_post_copyright clearfix">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <article class="box-left">
    <img src="https://gitee.com/lilyn/pic/raw/master/logo.jpg">
  </article>
  <article class="box-right">
    <p><span>本文标题:</span><a href="/posts/9f5130f2/">前后端 JS 加密常用方法（非对称加密、对称加密）</a></p>
    <p><span>文章作者:</span><a href="/" title="访问 LiLyn 的个人博客">LiLyn</a></p>
    <p><span>原始链接:</span><a href="/posts/9f5130f2/" title="前后端 JS 加密常用方法（非对称加密、对称加密）">http://llmysnow.top/posts/9f5130f2/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://llmysnow.top/posts/9f5130f2/"  aria-label="复制成功！"></i></span>
  </p>
    <p><span>许可协议:</span>转载请保留原文链接及作者。</p>  
  </article>
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

		  
	</div>

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Vue/" rel="tag"><i class="fa fa-tag"></i> Vue</a>
              <a href="/tags/RSA/" rel="tag"><i class="fa fa-tag"></i> RSA</a>
              <a href="/tags/MD5/" rel="tag"><i class="fa fa-tag"></i> MD5</a>
              <a href="/tags/SHA/" rel="tag"><i class="fa fa-tag"></i> SHA</a>
              <a href="/tags/AES/" rel="tag"><i class="fa fa-tag"></i> AES</a>
          </div>
		 
		<!--post-tags 彩色标签-->
		<script type="text/javascript">
		var tagsall=document.getElementsByClassName("post-tags")
		for (var i = tagsall.length - 1; i >= 0; i--){
			var tags=tagsall[i].getElementsByTagName("a");
			for (var j = tags.length - 1; j >= 0; j--) {
				var r=Math.floor(Math.random()*75+130);
				var g=Math.floor(Math.random()*75+100);
				var b=Math.floor(Math.random()*75+80);
				tags[j].style.background = "rgb("+r+","+g+","+b+")";
				tags[j].style.color = "#fff";
				tags[j].style.padding = "0 10px";
			}
		}                        
		</script>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/5b8836c3/" rel="prev" title="Vue 中使用 Upload 组件上传图片">
      <i class="fa fa-chevron-left"></i> Vue 中使用 Upload 组件上传图片
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/379f43e/" rel="next" title="Element 日期选择器清除问题（Axios get请求问题）">
      Element 日期选择器清除问题（Axios get请求问题） <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86"><span class="nav-text">对称加密</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%8D%E5%8F%AF%E9%80%86%E5%8A%A0%E5%AF%86%EF%BC%88MD5-SHA%EF%BC%89"><span class="nav-text">不可逆加密（MD5 SHA）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#crypto-%E8%BF%9B%E8%A1%8C-MD5-SHA-%E5%8A%A0%E5%AF%86"><span class="nav-text">crypto 进行 MD5 SHA 加密</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%8A%E9%9D%A2%E7%89%88%E6%9C%AC%E7%9A%84%E5%8A%A0%E7%9B%90%E5%92%8C-hmac-%E7%AE%97%E6%B3%95"><span class="nav-text">* 上面版本的加盐和 hmac 算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#blueimp-md5-%E8%BF%9B%E8%A1%8C-MD5-%E5%8A%A0%E5%AF%86"><span class="nav-text">blueimp-md5 进行 MD5 加密</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#sha-%E8%BF%9B%E8%A1%8C-SHA-%E5%8A%A0%E5%AF%86"><span class="nav-text">sha 进行 SHA 加密</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%AF%E9%80%86%E5%8A%A0%E5%AF%86%EF%BC%88AES-DES-BASE64%EF%BC%89"><span class="nav-text">可逆加密（AES DES BASE64）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#crypto-%E8%BF%9B%E8%A1%8C-AES-%E5%8A%A0%E5%AF%86"><span class="nav-text">crypto 进行 AES 加密</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#crypto-js-%E8%BF%9B%E8%A1%8C-AES-%E5%8A%A0%E5%AF%86"><span class="nav-text">* crypto-js 进行 AES 加密</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#crypto-js-%E8%BF%9B%E8%A1%8C-DES-%E5%8A%A0%E5%AF%86"><span class="nav-text">crypto-js 进行 DES 加密</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#crypto-js-%E8%BF%9B%E8%A1%8C-BASE64-%E5%8A%A0%E5%AF%86"><span class="nav-text">crypto-js 进行 BASE64 加密</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%9D%9E%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86"><span class="nav-text">非对称加密</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#jsencrypt-%E8%BF%9B%E8%A1%8C-RSA-%E5%8A%A0%E5%AF%86"><span class="nav-text">jsencrypt 进行 RSA 加密</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#node-rsa-%E8%BF%9B%E8%A1%8C-RSA-%E5%8A%A0%E5%AF%86"><span class="nav-text">node-rsa 进行 RSA 加密</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E5%90%8E%E7%AB%AF%E6%8E%A5%E5%8F%A3%E5%8A%A0%E5%AF%86"><span class="nav-text">前后端接口加密</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="LiLyn"
      src="/images/logo.jpg">
  <p class="site-author-name" itemprop="name">LiLyn</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">70</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">162</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/llwodexue" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;llwodexue" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/qq_38689395" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_38689395" rel="noopener" target="_blank"><i class="fas fa-copyright fa-fw"></i>CSDN</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://scx69.gitee.io/blogs/" title="https:&#x2F;&#x2F;scx69.gitee.io&#x2F;blogs&#x2F;" rel="noopener" target="_blank">花开满城</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://yixin-oss.gitee.io/daytoy/" title="http:&#x2F;&#x2F;yixin-oss.gitee.io&#x2F;daytoy&#x2F;" rel="noopener" target="_blank">daytoy</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LiLyn</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">463k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:01</span>
</div>

<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>-->

<!--
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>-->

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  

  <!-- 动态线条背景 -->
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  <!-- 页面点击小红心 -->
  <script type="text/javascript">
	!function(e,t,a){function n(){c(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"),o(),r()}function r(){for(var e=0;e<d.length;e++)d[e].alpha<=0?(t.body.removeChild(d[e].el),d.splice(e,1)):(d[e].y--,d[e].scale+=.004,d[e].alpha-=.013,d[e].el.style.cssText="left:"+d[e].x+"px;top:"+d[e].y+"px;opacity:"+d[e].alpha+";transform:scale("+d[e].scale+","+d[e].scale+") rotate(45deg);background:"+d[e].color+";z-index:99999");requestAnimationFrame(r)}function o(){var t="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){t&&t(),i(e)}}function i(e){var a=t.createElement("div");a.className="heart",d.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:s()}),t.body.appendChild(a)}function c(e){var a=t.createElement("style");a.type="text/css";try{a.appendChild(t.createTextNode(e))}catch(t){a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}var d=[];e.requestAnimationFrame=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)}}(),n()}(window,document);
  </script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body>
</html>